package com.pet.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pet.context.BaseContext;
import com.pet.dto.web.CheckResultDTO;
import com.pet.dto.web.PetAdoptInfoDTO;
import com.pet.entity.*;
import com.pet.exchange.PetAdoptInfoUtil;
import com.pet.exchange.PetInfoUtil;
import com.pet.mapper.PetAdoptApplicationMapper;
import com.pet.mapper.PetAdoptMapper;
import com.pet.mapper.PetInformationMapper;
import com.pet.mapper.UserInformationMapper;
import com.pet.pageDto.PetAdoptPageDTO;
import com.pet.result.PageResult;
import com.pet.service.PetAdoptService;
import com.pet.exchange.PetAdoptApplicationUtil;
import com.pet.vo.web.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class PetAdoptServiceImpl implements PetAdoptService {

    @Autowired
    private PetAdoptMapper petAdoptMapper;

    @Autowired
    private UserInformationMapper userInformationMapper;
    @Autowired
    private PetAdoptApplicationUtil petAdoptApplicationUtil;
    @Autowired
    private PetInformationMapper petInformationMapper;
    @Autowired
    private PetInfoUtil petInfoUtil;
    @Autowired
    private PetAdoptApplicationMapper petAdoptApplicationMapper;
    @Autowired
    private PetAdoptInfoUtil petAdoptInfoUtil;



    /**
     * 分页查询宠物送养信息
     * @param dto
     * @return
     */
    public PageResult pageQuery(PetAdoptPageDTO dto) {
        Page<PetAdoptInfoVO> page = new Page<>();

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //使用dishPageQueryDTO作为参数，执行一个分页查询，并将查询结果（一个Page对象，其中包含了DishVO类型的元素）存储在page变量中。
        Page<PetAdoptInfo> entity = petAdoptMapper.pageQuery(dto);
        log.info("{}",entity);

        for (PetAdoptInfo e : entity) {
            PetAdoptInfoVO vo = new PetAdoptInfoVO();
            BeanUtils.copyProperties(e, vo);
            //处理宠物信息
            PetInformation petInformation = petInformationMapper.selectPetInfoById(Math.toIntExact(e.getPetId()));
            PetInformationVO petInformationVO = new PetInformationVO();
            //赋值
            BeanUtils.copyProperties(petInformation,petInformationVO);
            //修改
            petInformationVO.setVaccine(String.valueOf(petInformation.getVaccine()));
            petInformationVO.setSterilization(String.valueOf(petInformation.getSterilization()));
            petInformationVO.setInsectRepellent(String.valueOf(petInformation.getInsectRepellent()));
            vo.setPetAdoptStatus(petAdoptInfoUtil.exchangePetAdoptInfo_petAdoptStatus(e.getPetAdoptStatus()));
            //处理创建人
            petInformationVO.setCreateUser(userInformationMapper.selectName(petInformation.getCreateUser()));
            vo.setPetInformationVO(petInformationVO);
            log.info("{}",e);

            //加入列表
            page.add(vo);
        }
        log.info("{}",page);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 分页查询宠物送养信息 管理员
     * @param dto
     * @return
     */
    public PageResult pageQueryAdmin(PetAdoptPageDTO dto) {
        Page<PetAdoptInfoVO> page = new Page<>();

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //使用dishPageQueryDTO作为参数，执行一个分页查询，并将查询结果（一个Page对象，其中包含了DishVO类型的元素）存储在page变量中。
        Page<PetAdoptInfo> entity = petAdoptMapper.pageQuery(dto);
        log.info("{}",entity);

        for (PetAdoptInfo e : entity) {
            PetAdoptInfoVO vo = new PetAdoptInfoVO();
            BeanUtils.copyProperties(e, vo);
            //处理宠物信息
            PetInformation petInformation = petInformationMapper.selectPetInfoById(Math.toIntExact(e.getPetId()));
            PetInformationVO petInformationVO = new PetInformationVO();
            //赋值
            BeanUtils.copyProperties(petInformation,petInformationVO);
            //修改
            petInformationVO.setVaccine(String.valueOf(petInformation.getVaccine()));
            petInformationVO.setSterilization(String.valueOf(petInformation.getSterilization()));
            petInformationVO.setInsectRepellent(String.valueOf(petInformation.getInsectRepellent()));
            vo.setPetAdoptStatus(petAdoptInfoUtil.exchangePetAdoptInfo_petAdoptStatus(e.getPetAdoptStatus()));
            //处理创建人
            petInformationVO.setCreateUser(userInformationMapper.selectName(petInformation.getCreateUser()));
            vo.setPetInformationVO(petInformationVO);
            log.info("{}",e);
            //处理送养人个人信息
            UserInformation userInformation = userInformationMapper.selectUserInformation(Long.valueOf(petInformation.getCreateUser()));
            if(userInformation != null){
                UserInformationVO userInformationVO = new UserInformationVO();
                BeanUtils.copyProperties(userInformation,userInformationVO);
                userInformationVO.setCreateUserId(userInformation.getId());
                //传入vo
                vo.setUserInformationVO(userInformationVO);
            }

            //加入列表
            page.add(vo);
        }
        log.info("{}",page);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 发布宠物送养信息
     * @param dto
     */
    public void postPetAdoptInfo(PetAdoptInfoDTO dto) {
        //获取当前用户id
        Long id = BaseContext.getCurrentId();
        //生成对应实体类
        PetAdoptInfo e = new PetAdoptInfo();
        //将dto进行插入
        BeanUtils.copyProperties(dto,e);
        e.setUserId(id);
        e.setPublishTime(LocalDate.now());

        petAdoptMapper.insertPetAdoptInfo(e);

    }

    /**
     * 删除宠物送养信息
     * @param id
     */
    @Transactional
    public void deletePetAdoptInfo(Integer id) {
        Long petId = null;
        //根据表id 获取宠物id
        petId =  petAdoptMapper.selectPetIdById(id);
        if(petId != null){
            //删除用户的送养信息
            petAdoptMapper.deletePetAdoptInfo(id);
            //根据宠物id 修改申请人表的状态和失败原因
            CheckResult checkResult = new CheckResult();
            checkResult.setFailureReason("送养人已删除送养信息");
            checkResult.setCheckResult(2);
            checkResult.setId(Math.toIntExact(petId));
            petAdoptMapper.PetAdoptCheckByPetId(checkResult);
            log.info("完成修改：{}",checkResult);
        }else {
            log.info("错误");
        }

    }

    /**
     * 修改宠物送养信息
     * @param dto
     */
    public void UpdatePetAdoptInfo(PetAdoptInfoDTO dto) {
        PetAdoptInfo e = new PetAdoptInfo();
        BeanUtils.copyProperties(dto,e);
        e.setPublishTime(LocalDate.now());
        petAdoptMapper.UpdatePetAdoptInfo(e);
    }

    /**
     * 查询个人宠物送养信息
     * @return
     */
    public List<PetAdoptInfoVO> GetPetAdoptInfo(Integer userId) {
        if (userId == null){
            userId = Math.toIntExact(BaseContext.getCurrentId());
        }
        //生成vo数组
        List<PetAdoptInfoVO> voList = new ArrayList<>();
        //根据用户id进行查询
        List<PetAdoptInfo> eList = petAdoptMapper.GetPetAdoptInfoById(userId);
        //遍历
        for (PetAdoptInfo petAdoptInfo : eList) {
            PetAdoptInfoVO vo = new PetAdoptInfoVO();
            BeanUtils.copyProperties(petAdoptInfo,vo);
            log.info("petAdoptInfo:{}",petAdoptInfo);
            //处理宠物信息
            //获取宠物信息
            PetInformation petInformation = petInformationMapper.selectPetInfoById(Math.toIntExact(petAdoptInfo.getPetId()));
            PetInformationVO petInformationVO = new PetInformationVO();
            BeanUtils.copyProperties(petInformation,petInformationVO);
            //修改字段
            petInformationVO.setVaccine(String.valueOf(petInformation.getVaccine()));
            petInformationVO.setSterilization(String.valueOf(petInformation.getSterilization()));
            petInformationVO.setInsectRepellent(String.valueOf(petInformation.getInsectRepellent()));
            vo.setPetAdoptStatus(petAdoptInfoUtil.exchangePetAdoptInfo_petAdoptStatus(petAdoptInfo.getPetAdoptStatus()));
            //处理创建人
            petInformationVO.setCreateUser(userInformationMapper.selectName(petInformation.getCreateUser()));
            vo.setPetInformationVO(petInformationVO);
            log.info("PetAdoptInfoVO:{}",vo);
            voList.add(vo);
        }

        return voList;
    }

    /**
     * 查询宠物送养详细信息
     * @param id
     * @return
     */
    @Transactional
    public PetAdoptInfoVO showPetAdoptInfo(Integer id) {
        //处理送养信息
        PetAdoptInfo petAdoptInfo = petAdoptMapper.showPetAdoptInfo(id);
        PetAdoptInfoVO petAdoptInfoVO = new PetAdoptInfoVO();
        if(petAdoptInfo != null){
            BeanUtils.copyProperties(petAdoptInfo,petAdoptInfoVO);
            //处理宠物信息
            PetInformation petInformation = petInformationMapper.selectPetInfoById(Math.toIntExact(petAdoptInfo.getPetId()));
            PetInformationVO petInformationVO = new PetInformationVO();
            petInformationVO = petInfoUtil.exchangePetInfoUtil(petInformation);
            //处理送养人个人信息
            UserInformation userInformation = userInformationMapper.selectUserInformation(Long.valueOf(petInformation.getCreateUser()));

            if(userInformation != null){
                UserInformationVO userInformationVO = new UserInformationVO();
                BeanUtils.copyProperties(userInformation,userInformationVO);
                petAdoptInfoVO.setUserInformationVO(userInformationVO);
            }
            //处理创建人
            petInformationVO.setCreateUser(userInformationMapper.selectName(petInformation.getCreateUser()));
            petAdoptInfoVO.setPetInformationVO(petInformationVO);
            petAdoptInfoVO.setPetAdoptStatus(petAdoptInfoUtil.exchangePetAdoptInfo_petAdoptStatus(petAdoptInfo.getPetAdoptStatus()));
        }
        return petAdoptInfoVO;
    }

    /**
     * 审核送养申请
     * @param dto
     */
    public void PetAdoptCheck(CheckResultDTO dto) {
        log.info("{}",dto);
        CheckResult e = new CheckResult();
        BeanUtils.copyProperties(dto,e);
        //修改宠物申请表信息
        petAdoptMapper.PetAdoptCheck(e);
        //如果申请成功 修改宠物送养表信息 将字段pet_adopt_status改为1 将其他申请状态改为2（申请失败）
        if (e.getCheckResult() == 1){
            //1、根据e.getId获取petId
            Long petId = petAdoptMapper.selectPetIdByIdFromApplication(dto.getId());
            log.info("petId:{}",petId);
            //修改宠物送养表信息 将该宠物领养状态改为1（已经被领养）
            petAdoptMapper.updatePetAdoptStatus(1, Math.toIntExact(petId));
            //将其他申请状态改为2（申请失败）
            //2、根据petId获取其他申请列表
            List<PetAdoptApplication> petAdoptApplicationList =
                    petAdoptApplicationMapper.selectPetAdoptApplicationByPetId(petId);
            //3、将其他申请状态改为2（申请失败）
            if (petAdoptApplicationList != null){
                log.info("petAdoptApplicationList:{}",petAdoptApplicationList);
                for (PetAdoptApplication petAdoptApplication : petAdoptApplicationList) {
                   //排除当前申请
                    if(!Objects.equals(petAdoptApplication.getId(), e.getId())){
                        CheckResult checkResult = new CheckResult();
                        checkResult.setFailureReason("宠物已经被领养");
                        checkResult.setCheckResult(2);
                        checkResult.setId(Math.toIntExact(petAdoptApplication.getId()));
                        petAdoptMapper.PetAdoptCheck(checkResult);
                    }
                }
            }
        }
    }

    /**
     * 根据用户id查询宠物id 查询领养申请
     * @return
     */
    @Transactional
    public List<PetAdoptApplicationVO> PetAdoptApplicationInfo() {
        List<PetAdoptApplicationVO> voList= new ArrayList<>();
        //根据用户id查询宠物id <pet_adopt_info>
        List<Integer> petId = petAdoptMapper.selectPetIdByUserId(BaseContext.getCurrentId());
        for (Integer i : petId) {
            //根据宠物id查询申请
            List<PetAdoptApplication> eList = petAdoptMapper.PetAdoptApplicationInfo(Long.valueOf(i));
            //获取宠物信息
            PetInformation petInformation = petInformationMapper.selectPetInfoById(i);
            PetInformationVO petInformationVO =  petInfoUtil.exchangePetInfoUtil(petInformation);
            //遍历修改
            for (PetAdoptApplication petAdoptApplication : eList) {
                PetAdoptApplicationVO vo = petAdoptApplicationUtil.exchangePetAdoptApplicationUtil(petAdoptApplication);
                vo.setPetInformationVO(petInformationVO);
                //设置申请人头像
                vo.setApplicationUserImage(userInformationMapper.selectProfilePhotoById(petAdoptApplication.getApplicationUser()));
                voList.add(vo);
            }
        }
        log.info("{}-{}",petId,voList);
        return voList;
    }

    /**
     * 审核送养
     * @param dto
     */
    public void checkUserAdopt(CheckResultDTO dto) {
        CheckResult checkResult = new CheckResult();
        BeanUtils.copyProperties(dto,checkResult);
        petAdoptMapper.PetAdoptCheck(checkResult);
    }

    /**
     * 查询个人已经送养的宠物信息
     * @return
     */
    public List<PetAdoptedInfoVO> PetAdoptApplicationInfoByStatus() {
        List<PetAdoptedInfoVO> petAdoptedInfoVOS = new ArrayList<>();
        //查询petAdoptInfo获取petId列表
        List<Integer> petIdList = petInformationMapper.selectPetIdListByUserId(BaseContext.getCurrentId());
        log.info("{}",petIdList);
        //遍历petId列表获取申请人信息和动物信息
        for (Integer i : petIdList) {
            //查询宠物信息
            PetInformation petInformation = petInformationMapper.selectPetInfoById(i);
            log.info("{}",petInformation);
            //e - vo
            PetInformationVO petInformationVO = petInfoUtil.exchangePetInfoUtil(petInformation);

            //查询petAdoptApplication表 获取审核通过的领养人信息
            Integer checkStatus = 1;//1表示成功状态
            PetAdoptApplication petAdoptApplication =
                    petAdoptApplicationMapper.selectPetAdoptApplicationByPetIdAndStatus(i,checkStatus);
            log.info("{}",petAdoptApplication);
            //声明
            PetAdoptApplicationVO petAdoptApplicationVO = new PetAdoptApplicationVO();
            //赋值
            if (petAdoptApplication != null){
                petAdoptApplicationVO = petAdoptApplicationUtil.exchangePetAdoptApplicationUtil(petAdoptApplication);
                petAdoptApplicationVO.setPetInformationVO(petInformationVO);
            }
            //声明，赋值
            PetAdoptedInfoVO petAdoptedInfoVO = new PetAdoptedInfoVO();
            petAdoptedInfoVO.setPetAdoptApplicationVO(petAdoptApplicationVO);
            //添加入数组
            if(petAdoptApplication != null){
                petAdoptedInfoVOS.add(petAdoptedInfoVO);
            }
        }


        return petAdoptedInfoVOS;
    }
}
